<?php
/**
 * Created by PhpStorm.
 * User: prg
 * Date: 2017/2/11
 * Time: 23:04
 */

class Db {
    //用来保存类的实例的静态成员变量
    static private $_instance;
    //保存数据库连接用的数据的数组
    private $_dbConfig = array(
        'host'=>'127.0.0.1',
        'user'=>'root',
        'password'=>'',
        'database'=>'cyxy',
    );
    //保存数据库资源句柄的静态成员变量
    static private $_connectSource;

    //构造函数非public，就会让new操作符无法创建实例了
    private function __construct()
    {
    }

    //这个静态的公有方法是用来实例化对象的
    static public function getInstance() {
        //进行判断，如果已经实例化过，就不会再重新实例化了，用instanceof self 进行判断
        if(!(self::$_instance instanceof self)) {
            //注意是如何实例化的
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    //用来连接数据库的公有方法
    public function connect() {
        //如果这个资源不存在才进行数据库连接，这样就不会重复浪费资源

        if(!self::$_connectSource) {
            //返回的是一个资源句柄
            self::$_connectSource = mysqli_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);

            if (!self::$_connectSource) {
//                die('mysql connect error'.mysqli_error(self::$_connectSource));
                //抛出异常
                throw new Exception('mysql connect error' . self::$_connectSource->error);
            }
            //选择一个数据库操作
            mysqli_select_db(self::$_connectSource, $this->_dbConfig['database']);

            //设置字符集
            mysqli_set_charset(self::$_connectSource, "UTF8");
        }
        return self::$_connectSource;
    }

}

//$connect = Db::getInstance()->connect();
//
//$sql = "SELECT * FROM user";
//$result = mysqli_query($connect,$sql);
//
//echo $result->num_rows;
//var_dump($result);